import { BadRequestException, CanActivate, ExecutionContext, Inject, Injectable, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { JwtService } from 'src/libs/jwt/jwt.service';
import { PrismaService } from 'src/libs/prisma/prisma.service';

// 温度和积分映射关系
export const getPointByTemperature = (temperature: number) => {
  if (temperature <= 0.3) return 2;
  if (temperature <= 0.7) return 4;
  if (temperature <= 1.1) return 6;
  if (temperature <= 1.5) return 8;
  return 8;
};

@Injectable()
export class UsePointGuard implements CanActivate {
  @Inject(PrismaService)
  private prisma: PrismaService;

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request: Request = context.switchToHttp().getRequest();
    // 1 用户不存在
    if (!request.user) throw new UnauthorizedException('用户未登录');
    // 2 获取用户信息
    const userItem = await this.prisma.user.findUnique({ where: { id: request.user.userId } });
    if (!userItem) throw new UnauthorizedException('用户不存在');
    // 3 如果用户积分不足
    const temperature = request.query?.temperature || 0.3;
    const usePoint = getPointByTemperature(+temperature);
    if (userItem.points < usePoint) throw new BadRequestException('用户积分不足');
    // 4 扣除积分
    await this.prisma.user.update({
      where: { id: request.user.userId },
      data: { points: { decrement: usePoint } },
    });

    return true;
  }
}
